package com.hqyj.springbootday03.modules.test.service.impl;

import com.github.pagehelper.Page;
import com.hqyj.springbootday03.modules.common.vo.Result;
import com.hqyj.springbootday03.modules.common.vo.Search;
import com.hqyj.springbootday03.modules.test.dao.StudentDao;
import com.hqyj.springbootday03.modules.test.entity.Student;
import com.hqyj.springbootday03.modules.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    @Transactional
    public Result<Student> editStudent(Student student) {
        studentDao.saveAndFlush(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code,"更新成功",student);
    }

    @Override
    public Student getStudentById(int id) {
        return studentDao.getById(id);
    }

    @Override
    public Student getStudentByStudentName(String studentName) {
        List<Student> list = Optional
                .ofNullable(studentDao.findByStudentName(studentName))
                .orElse(Collections.emptyList());
        return list.isEmpty() ?  null : list.get(0);
    }

    @Override
    @Transactional
    public Result<Student> updateStudent(Student student) {
        studentDao.updateStudent(student);
        return new Result<>(Result.ResultStatus.SUCCESS.code, "修改成功.", student);
    }

    @Override
    public Page<Student> getStudentsBySearch(Search search) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Sort sort = Sort.by(order);
        Pageable pageable = PageRequest.of(search.getCurrentPage() - 1, search.getPageSize(), sort);

        Student student = new Student();
        student.setStudentName(search.getKeyword());
        ExampleMatcher matcher = ExampleMatcher.matchingAny()
                .withMatcher("studentName", match -> match.contains())
                .withIgnorePaths("id", "age");
        Example<Student> example = Example.of(student, matcher);

//        return studentDao.findAll(example, pageable);
        return null;
    }
}
